<?php

namespace control;
/*
*工序库存表类
*/

class processInventoryClass extends adIndexClass
{
    private const page = 'processInventory';
    private const table = 'process_material_record';
    private const title = '工序库存表';

    /**
     * 字段初始化
     */
    public function fieldInit($fun): array
    {
        switch ($fun) {
            default:
                $tr = [
                    'code'          => [
                        'name'  => "物料编码",
                        'width' => 250,
                    ],
                    'name'  => [
                        'name'  => '物料名称',
                        'width' => 250,
                    ],
                    'typeName'         => [
                        'name'  => '物料分类',
                        'width' => 250,
                    ],
                    'model'          => [
                        'name'  => '规格型号',
                        'width' => 250,
                    ],
                    'unit'          => [
                        'name'  => '主单位',
                        'width' => 250,
                    ],
                    'num'          => [
                        'name'  => '工序总合格数量',
                        'width' => 250,
                    ]
                ];
        }
        return $tr;
    }

    /*列表页-查询条件*/
    public function homeOptions($isAsync = true)
    {
        //生成查询表单
        $html = $this->tableShow([
            [
                [
                    "物料编码"   => text(array("name" => "code")),
                    "物料名称"   => text(array("name" => "name")),
                    "规格型号"   => text(array("name" => "model")),
                ],
                [
                    "物料分类" => materialClass::typeSelect(title: '请选择'),
                ]
            ]
        ],1);
        //返回
        if (!$isAsync) {
            return $html;
        } else {
            return json_encode(['html' => $html], 320);
        }
    }

    /*列表-查询条件*/
    public function home()
    {
        $html = $this->homeOptions(false);
        //控件
        $button = "";
        if ($this->power(self::page, "export")) {
            $button .="<span class='spanButton' onclick=\"layer('importTemplate','exportFrame',{cla:'".self::page."'})\">导出</span>";
        }
        //返回
        return $this->homeFun($this->search($html, layout: 'pop', toolButton: $button));
    }

    /*客户列表-查询结果*/
    public function homeSearch()
    {
        //like查询数组
        $like = array(
            "b.code" => $this->post('code'),
            "b.name" => $this->post('name'),
            "b.model" => $this->post('model'),
        );
        //全等查询数组
        $equal = array(
            "a.coid"=>self::$coid,
            "b.typePath" => $this->post('materialTypeId'),
        );
        $and = " and 1=1";
        //排序
        $orderBy = $this->listSort(array(
            "search"  => $this->post('list_sort_key') ?: 'materialId',
            "sort" => $this->post('list_sort') ?: "desc",
            "array"   => array(),
        ));
        //获取查询结果
        $where = search(array("like" => $like, "=" => $equal)) . $and . " group by a.materialId";
        $page = $this->page(array(
            "table" => self::table . " as a join material as b on a.materialId = b.id",
            'field' => "a.materialId",
            "where" => $where,
            "order" => $orderBy['orderBy']
        ));
        $_SESSION[self::page]['sql'] = $page['fullSql'];
        //获取自定义字段参数
        $installSearch = $this->installSearch();
        $body          = [];
        //表格控件区
        $liButton = array("");
        //获取记录
        $url = root . "control/adIndex.html?cla=" . self::page;
        foreach ($page['array'] as $array) {
            //列表控件
            $dominate = array(
                "detail" => array("title" => self::title . "详情", "click" => "newIframe('" . self::title . "详情','" . $url . "&fun=detail&id=" . $array['materialId'] . "')"),
            );
            $material = query('material', "id = '$array[materialId]'");
            $liButton[] = $this->dominate($dominate);
            //本行初始化
            $row = [];
            foreach ($installSearch['key'] as $key) {
                switch ($key) {
                    case 'code':
                    case 'name':
                    case 'typeName':
                    case 'model':
                    case 'unit':
                        $row[] = $material[$key];
                        break;
                    case 'num':
                        $row[] = self::inventoryNum($material['id']);
                        break;
                    default:
                        $row[] = isset($array[$key]) && $array[$key] ? $array[$key] : '';
                }
            }
            $body[] = $row;
        }
        $totalQuery = find([
            'table'  => self::table . " as a join material as b on a.materialId = b.id",
            'single' => $where,
            'field'  => "ifnull(sum(num),0) as num",
        ]);
        $total    = [
            'num'        => self::lostZero($totalQuery['num'], 'numPrecision'),
        ];
        //生成页面
        $li = $this->li(array(
            "body" => $body,
            "install" => $installSearch,
            "button" => array("html" => $liButton),
            "orderBySign" => $orderBy,
            "page" => $page['para'],
            "total"       => $total,
        ));
        //返回
        $json['html'] = $page['hint'] . "<form name='listForm'>" . $li . "</form>" . $page['button'] . clear;
        return json_encode($json, 320);
    }

    /**
     * 新增工序库存数据
     */
    public static function iData($data)
    {
        $data['coid'] = self::$coid;
        return self::insert(array('table' => self::table, 'field' => $data));
    }

    /**
     * 删除工序库存数据
     * @param $id
     * @return string
     */
    public static function delData($id)
    {
        return delete(array('table' => self::table, 'where' => "sourceId = '$id'"));
    }

    /**
     * 获取库存数量
     * @param $materialId
     * @param string $processId
     * @return float
     */
    public static function inventoryNum($materialId, $processId = '')
    {
        $where = '';
        if ($processId) {
            $where .= " and processId = '$processId'";
        }
        $num = find([
            'table' => self::table,
            'single' => "coid = '" . self::$coid . "' and materialId = '$materialId' " . $where,
            'field' => "ifnull(sum(num),0) as num"
        ])['num'];
        return floatval($num);
    }

    /**
     * 导出
     */
    public function exportData()
    {
        $templateId = $this->get('templateId');
        if (!$this->power(self::page, 'export')) {
            $_SESSION['warn'] = '你还没有导出的权限';
        }  else {
            $data = [];
            /***********标题**********/
            $title =[];
            $tempFieldAll = importTemplateClass::templateField(self::page, 'exportFieldInit', id:$templateId);
            foreach ($tempFieldAll as $array) {
                if ($array['display']){
                    $title[] = $array['aliasName'];
                }
            }
            $sql   = $_SESSION[self::page]['sql'];
            $result   = sqlFind($sql);
            //导出数据生成
            foreach ($result as $array){
                $column = [];
                $material = query('material', "id = '$array[materialId]'");
                $all = find([
                    'table'=>self::table." as a join process as b on a.processId = b.id",
                    'field'=>"distinct a.materialId,a.processId",
                    'where'=>"a.coid = '".self::$coid."' and a.materialId = '$array[materialId]'"
                ]);
                //获取表头
                foreach ($all['array'] as $val){
                    $process = query('process',"id = '$val[processId]'");
                    foreach ($tempFieldAll as $templateField){
                        if ($templateField['display']){
                            $column[] = match ($templateField['columnName']){
                                '物料编码'=>$material['code'],
                                '物料名称'=>$material['name'],
                                '物料分类'=>$material['typeName'],
                                '规格型号'=>$material['model'],
                                '主单位'=>$material['unit'],
                                '工序'=> $process['name'],
                                '合格数量'=>self::inventoryNum($array['materialId'],$val['processId']),
                                default=>'',
                            };
                        }
                    }
                    $data[] = $column;
                }

            }

            $text = $this->control['name'] . "导出了".self::title;
            $this->logText(["type" => self::page, "text" => $text]);
            $this->excelOut($title, $data, self::title.".xlsx");
            exit(0);
        }
        header("Location:" . getenv("HTTP_REFERER"));

    }

    /*详情页*/
    public function detail(): string
    {
        $materialId = $this->get('id');
        if (empty($materialId)) {
            $html = '未找到此物料ID';
        } else {
            //菜单
            $data = array(
                "id" => $materialId,
            );
            $material = query('material', "id = '$materialId'");
            //生成表单
            $data['html'] = $this->tableShow(array(
                '基本信息' => array(
                    array(
                        "物料分类" => $material['typeName'],
                        "物料编码" => $material['code'],
                        "物料名称" => $material['name'],
                        "规格型号" => $material['model'],
                    ),
                    array(
                        "主单位" => $material['unit'],
                        "工序总合格数量" => self::inventoryNum($materialId),
                    ),
                ),
            ));
            $data['html'] .= $this->detailList([
                'title' => '工序库存明细',
                'html' => $this->inventoryMx($materialId),
            ]);
            $data['html'] .= "<style>[searchformhtml]{padding: 0!important;}.search{margin: 5px 0;}</style>";
            //生成页面
            $html = $this->tab($data);
        }
        //返回
        return $html;
    }

    /**
     * 工序库存明细
     */
    public function inventoryMx($materialId)
    {
        $html =
            text(array("name" => "processName", "title" => '工序')) .
            hidden(array('name' => 'materialId', 'value' =>$materialId));
        return $this->search($html,fun:'inventoryMxSearch');
    }

    public function inventoryMxSearch()
    {
        $materialId = $this->post('materialId');
        $like = [
            'b.name' => $this->post('processName'),
        ];
        $equal = [

        ];
        $where = search(["like" => $like, "=" => $equal]);
        $all = find([
            'table'=>self::table." as a join process as b on a.processId = b.id",
            'field'=>"distinct a.materialId,a.processId",
            'where'=>$where." and a.coid = '".self::$coid."' and a.materialId = '$materialId'"
        ]);
        //获取表头
        $tr[] = ['工序名称', '库存数量'];
        $totalNum = 0;
        foreach ($all['array'] as $array){
            $process = query('process',"id = '$array[processId]'");
            $inventoryNum = self::inventoryNum($array['materialId'],$array['processId']);
            $tr[] = array(
                $process['name'],
                $inventoryNum
            );
            $totalNum += $inventoryNum;
        }
        $total_tr = [
            1=>self::lostZero($totalNum,'numPrecision'),
        ];
        $json['html'] = $this->tableMany(array("tr" => $tr, 'showSort' => true, 'total' => $total_tr));
        return json_encode($json, 320);
    }

    /**
     * 导出模板字段初始化
     * @return array[]
     */
    public function exportFieldInit($classify=''): array
    {
        return match ($classify) {
            default=>  [
                [
                    'columnName'=>'物料编码',
                    'aliasName'=>'物料编码',
                ],
                [
                    'columnName'=>'物料名称',
                    'aliasName'=>'物料名称',
                ],
                [
                    'columnName'=>'物料分类',
                    'aliasName'=>'物料分类',
                ],
                [
                    'columnName'=>'规格型号',
                    'aliasName'=>'规格型号',
                ],
                [
                    'columnName'=>'主单位',
                    'aliasName'=>'主单位',
                ],
                [
                    'columnName'=>'工序',
                    'aliasName'=>'工序',
                ],
                [
                    'columnName'=>'合格数量',
                    'aliasName'=>'合格数量',
                ],
            ]
        };
    }
}

